use log::info;
use pingora::http::RequestHeader;
use substring::Substring;
use urlencoding::decode;
pub struct Loation {
    // 该location对应的前缀
    prefix: String,
    // 该location对应的upstream
    pub upstream: String,
    // 删除前缀
    replace: bool,
}

impl Loation {
    pub fn new(prefix: String, upstream: String, replace: bool) -> Self {
        Self {
            prefix,
            upstream,
            replace,
        }
    }
    pub fn matched(&self, path: &str) -> bool {
        // 判断是否包括该前缀
        path.starts_with(&self.prefix)
    }
    pub fn rewrite(&self, header: &mut RequestHeader) -> Option<String> {
        // 无需重写
        if !self.replace {
            return None;
        }
        let path = header.uri.path();
        let decoded_path = decode(path).unwrap_or(path.to_string().into()); // 解码路径
        let new_path = decoded_path.substring(self.prefix.len(), decoded_path.len());
        info!("Rewriting path: {} -> {}", decoded_path, new_path);
        let mut uri = new_path.to_string();
        if let Some(query) = header.uri.query() {
            uri = format!("{new_path}?{query}");
        }
        Some(uri)
    }
}
